package com.seocoo.worker.user;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.contrarywind.view.WheelView;
import com.jaeger.library.StatusBarUtil;
import com.seocoo.worker.R;
import com.seocoo.worker.WorkerAppContent;
import com.seocoo.worker.base.ImageLoaderEngine;
import com.seocoo.worker.base.ImageSelector;
import com.seocoo.worker.base.KeyboardUtil;
import com.seocoo.worker.base.PermissionUtil;
import com.seocoo.worker.base.city.SelectCityActivity;
import com.seocoo.worker.base.entity.EFile;
import com.seocoo.worker.base.widget.AppToolBer;
import com.seocoo.worker.base.widget.LtvRetLayout;
import com.seocoo.worker.base.widget.LtvRtvLayout;
import com.seocoo.worker.user.login.PlatformDialog;
import com.seocoo.worker.user.login.entity.EAdept;
import com.seocoo.worker.user.login.entity.ECraftsmanInfo;
import com.seocoo.worker.user.login.model.RegisterModel;
import com.seocoo.worker.user.login.model.ReqRegister;
import com.seocoo.worker.user.model.UserModel;
import com.seocoo.worker.user.model.request.ReqApplyMeasure;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.mvvm.LiveDataMatch;
import com.sfh.lib.ui.DialogBuilder;
import com.sfh.lib.ui.MVVMActivity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/***
 * 申请金牌
 */
public class ApplyGoldActivity extends MVVMActivity implements View.OnClickListener {


    private AppToolBer appToolBer;
    private LtvRetLayout leName;
    private LtvRetLayout lePhone;
    private LtvRetLayout leMail;
    private LtvRtvLayout lvAddress;
    private LtvRetLayout leIdcard;
    private LtvRtvLayout lvIdcardTime;
    private LtvRtvLayout lvGood;
    private ImageView ivIdcardZ;
    private ImageView ivIdcardF;
    private ImageView ivHanderPhoto;
    private TextView tvNext;
    private ReqApplyMeasure reqRegister = new ReqApplyMeasure();

    public static void start(Context context) {
        Intent intent = new Intent(context, ApplyGoldActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_apply_gold_activity);
        initView();
        StatusBarUtil.setTranslucentForImageView(this, 0, appToolBer);
        appToolBer.getTvRight().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getViewModel(UserModel.class).queryRule("3");
            }
        });
        appToolBer.getTvRight().setVisibility(View.GONE);
    }

    private void initView() {

        appToolBer = (AppToolBer) findViewById(R.id.appToolBer);
        leName = (LtvRetLayout) findViewById(R.id.le_name);
        lePhone = (LtvRetLayout) findViewById(R.id.le_phone);
        leMail = (LtvRetLayout) findViewById(R.id.le_mail);
        lvAddress = (LtvRtvLayout) findViewById(R.id.lv_address);
        leIdcard = (LtvRetLayout) findViewById(R.id.le_idcard);
        lvIdcardTime = (LtvRtvLayout) findViewById(R.id.lv_idcard_time);
        lvGood = (LtvRtvLayout) findViewById(R.id.lv_good);
        ivIdcardZ = (ImageView) findViewById(R.id.iv_idcard_z);
        ivIdcardF = (ImageView) findViewById(R.id.iv_idcard_f);
        ivHanderPhoto = (ImageView) findViewById(R.id.iv_hander_photo);
        tvNext = (TextView) findViewById(R.id.tv_next);

        appToolBer.getTvLeft().setOnClickListener(this);
        tvNext.setOnClickListener(this);
        ivIdcardZ.setOnClickListener(this);
        ivIdcardF.setOnClickListener(this);
        ivHanderPhoto.setOnClickListener(this);
        lvGood.getTvRight().setOnClickListener(this);
        lvIdcardTime.getTvRight().setOnClickListener(this);
        lvAddress.getTvRight().setOnClickListener(this);


        getViewModel(UserModel.class).queryCraftsmanInfo();
        getViewModel(UserModel.class).queryRuleShow("3");
    }
    @LiveDataMatch
    public void showRuleIcon(){
        appToolBer.getTvRight().setVisibility(View.VISIBLE);
    }
    @LiveDataMatch
    public void showRule(String msg){
        PlatformDialog.showDialogUI(this,"金牌工匠规则",msg);
    }

    @LiveDataMatch
    public void onCraftsmanInfo(ECraftsmanInfo info) {
        if (info == null) {
            return;
        }

        reqRegister.setAdept(info.adept);
        reqRegister.setAdeptDesc(info.adeptDesc);
        lvGood.getTvRight().setText(reqRegister.getAdeptDesc());

        reqRegister.setIdNumber(info.idNumber);
        leIdcard.getEtRight().setText(info.idNumber);

        reqRegister.setManId(info.manId);
        reqRegister.setPhoneNumber(info.phoneNumber);
        lePhone.getEtRight().setText(info.phoneNumber);

        reqRegister.setLocationLat(info.locationLat);
        reqRegister.setLocationLon(info.locationLon);
        reqRegister.setCityName(info.cityName);
        reqRegister.setCityCode(info.cityCode);
        lvAddress.getTvRight().setText(info.cityName);

        reqRegister.setRealName(info.realName);
        leName.getEtRight().setText(info.realName);


        reqRegister.setValidityStart(info.validityStart);
        reqRegister.setValidityEnd(info.validityEnd);
        lvIdcardTime.getTvRight().setText(info.validityStart + "~" + info.validityEnd);

        reqRegister.setEmail(info.email);
        leMail.getEtRight().setText(info.email);

        reqRegister.setReverse(info.reverse);
        reqRegister.setHandCard(info.handCard);
        reqRegister.setPositive(info.positive);


        new ImageLoaderEngine(info.visitUrl + info.positive).error(R.drawable.user_register_crad_r).into(ivIdcardZ);
        new ImageLoaderEngine(info.visitUrl + info.reverse).error(R.drawable.user_register_crad_g).into(ivIdcardF);
        new ImageLoaderEngine(info.visitUrl + info.handCard).error(R.drawable.base_photo).into(ivHanderPhoto);
    }


    @Override
    public void onClick(View v) {
        KeyboardUtil.hideKeyboard(v);

        if (appToolBer.getTvLeft() == v) {
            DialogBuilder builder = new DialogBuilder();
            builder.setMessage("确定放弃申请成为金牌工匠吗？");
            builder.setOkListener((dialog, which) -> {
                dialog.dismiss();
                finish();
            });
            showDialog(builder);

        } else if (v == lvAddress.getTvRight()) {

            SelectCityActivity.start(this, 1007);

        } else if (v == lvIdcardTime.getTvRight()) {
            creatDayTimePicker("身份证有效期开始", (date, v12) -> {
                reqRegister.setValidityStart(new SimpleDateFormat("yyyy-MM-dd").format(date));
                creatDayTimePicker("身份证有效期结束", (date1, v1) -> {
                    reqRegister.setValidityEnd(new SimpleDateFormat("yyyy-MM-dd").format(date1));

                    lvIdcardTime.getTvRight().setText(reqRegister.getValidityStart() + "~" + reqRegister.getValidityEnd());
                    String time = lvIdcardTime.getContent();
                    String[] times = time.split("~");
                    if (times.length != 2 || Long.valueOf(times[0].replace("-", "")) >= Long.valueOf(times[1].replace("-", ""))){
                        showToast("身份证有效期开始日期小于结束日期");
                        return;
                    }
                });
            });
        } else if (v == ivIdcardZ) {
            openPhoto(1001);

        } else if (v == lvGood.getTvRight()) {
            //擅长领域
            getViewModel(RegisterModel.class).queryAdeptList();
        } else if (v == ivIdcardF) {
            openPhoto(1002);
        } else if (v == ivHanderPhoto) {
            openPhoto(1003);
        } else if (v == tvNext) {
            String name = leName.getContent();
            if (TextUtils.isEmpty(name)) {
                showToast("请输入真实姓名");
                return;
            }
            reqRegister.setRealName(name);

            String phone = lePhone.getContent();
            if (TextUtils.isEmpty(name)) {
                showToast("请输入联系电话");
                return;
            }
            if (phone.length() != 11) {
                showToast("请输入联11位联系电话");
                return;
            }
            reqRegister.setPhoneNumber(phone);

            String address = lvAddress.getContent();
            if (TextUtils.isEmpty(address)) {
                showToast("请选择所在区域");
                return;
            }

            String idcard = leIdcard.getContent();
            if (TextUtils.isEmpty(idcard)) {
                showToast("请输入身份证号");
                return;
            }
            if (!idcard.matches("^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$")) {
                showToast("请输入18位身份证号");
                return;
            }
            reqRegister.setIdNumber(idcard);

            String time = lvIdcardTime.getContent();
            if (TextUtils.isEmpty(time)) {
                showToast("请选择身份证有效期");
                return;
            }
            String[] times = time.split("~");
            if (times.length != 2 || Long.valueOf(times[0].replace("-", "")) >= Long.valueOf(times[1].replace("-", ""))){
                showToast("身份证有效期开始日期小于结束日期");
                return;
            }

            String good = lvGood.getContent();
            if (TextUtils.isEmpty(good)) {
                showToast("请选择擅长领域");
                return;
            }

            if (TextUtils.isEmpty(reqRegister.getPositive())) {
                showToast("请上传身份证正面");
                return;
            }
            if (TextUtils.isEmpty(reqRegister.getReverse())) {
                showToast("请上传身份证反面");
                return;
            }
            if (TextUtils.isEmpty(reqRegister.getHandCard())) {
                showToast("请上传手持身份证照片");
                return;
            }

            reqRegister.setEmail(leMail.getContent());

            getViewModel(UserModel.class).applyMeasure(reqRegister);

        }

    }

    @LiveDataMatch
    public void onApplyMeasure() {
        showToast("提交审核成功！");
        WorkerAppContent appContent = (WorkerAppContent) getApplication();
        appContent.onExit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.onClick(appToolBer.getTvLeft());
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void openPhoto(int requestCode) {
        PermissionUtil.checkPermissions(this, "请允许访问相册与摄像头", 1011, new PermissionUtil.PermissionCallBack() {
            @Override
            public void onHasPermission() {
                ImageSelector.create().count(1).showCamera(true).start(ApplyGoldActivity.this, requestCode);
            }

            @Override
            public void onFailedPermission() {
                showDialogToast("授权失败！请");
            }
        }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1007) {
                reqRegister.setCityName(data.getStringExtra("name"));
                reqRegister.setCityCode(data.getStringExtra("code"));
                lvAddress.getTvRight().setText(data.getStringExtra("name"));
                return;
            }
            List<String> images = ImageSelector.onActivityResult(resultCode, data);
            if (images != null && images.isEmpty()) {
                return;
            }
            RegisterModel registerModel = getViewModel(RegisterModel.class);
            switch (requestCode) {
                case 1001: {
                    registerModel.uploadFile(1001, images.get(0));
                    break;
                }
                case 1002: {
                    registerModel.uploadFile(1002, images.get(0));
                    break;
                }
                case 1003: {
                    registerModel.uploadFile(1003, images.get(0));
                    break;
                }
                default:
                    break;
            }
        }
    }

    @LiveDataMatch
    public void onFileScuess(int requestCode, EFile file) {
        switch (requestCode) {
            case 1001: {
                new ImageLoaderEngine(file.getFullPath()).error(R.drawable.user_register_crad_r).into(ivIdcardZ);
                reqRegister.setPositive(file.getFileName());
                break;
            }
            case 1002: {
                new ImageLoaderEngine(file.getFullPath()).error(R.drawable.user_register_crad_g).into(ivIdcardF);
                reqRegister.setReverse(file.getFileName());
                break;
            }
            case 1003: {
                new ImageLoaderEngine(file.getFullPath()).error(R.drawable.base_photo).into(ivHanderPhoto);
                reqRegister.setHandCard(file.getFileName());
                break;
            }
            default:
                break;
        }
    }

    @LiveDataMatch
    public void onQueryAdeptListrScuess(List<EAdept> list) {

        String[] adept = null;
        if (!TextUtils.isEmpty(reqRegister.getAdept())) {
            adept = reqRegister.getAdept().split(",");
        }
        new AdeptDialog(this, list, adept,(dialog, list1) -> {
            dialog.dismiss();
            StringBuffer adpters = new StringBuffer();
            StringBuffer adpterDesc = new StringBuffer();
            for (EAdept it : list1) {
                adpters.append(it.classifyId).append(",");
                adpterDesc.append(it.classifyName).append(",");
            }
            if (adpters.length() > 0) {
                reqRegister.setAdept(adpters.substring(0, adpters.length() - 1));
                reqRegister.setAdeptDesc(adpterDesc.substring(0, adpterDesc.length() - 1));
                lvGood.getTvRight().setText(reqRegister.getAdeptDesc());
            } else {
                lvGood.getTvRight().setText("");
            }

        }).show(tvNext);
    }

    /**
     * 时间选择
     */
    private void creatDayTimePicker(String title, OnTimeSelectListener timeSelectListener) {

        //系统当前时间
        Calendar selectedDate = Calendar.getInstance();

        TimePickerBuilder timePickerBuilder = new TimePickerBuilder(this, timeSelectListener)
                .setTitleText(title)
                //时间选择器 ，自定义布局
                .setDividerColor(Color.parseColor("#999999"))
                .setDividerType(WheelView.DividerType.FILL)
                .setContentTextSize(20)
                .setDate(selectedDate)
                //设置选中项的颜色
                .setTextColorCenter(Color.parseColor("#333333"))
                .isCenterLabel(true)
                //设置两横线之间的间隔倍数  m
                .setLineSpacingMultiplier(2.0f)
                .setTextXOffset(0, 0, 0, 0, 0, 0)
                .setOutSideCancelable(false)
                .setType(new boolean[]{true, true, true, false, false, false});
        timePickerBuilder.build().show();
    }
}
